<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/8
 * Time: 20:13
 */

namespace app\base\controller;

use CMaker\Component;
use think\facade\Request;
use app\base\model;

/**
 * 角色管理
 */
class Role extends Common
{
    protected static $role ;
    protected static $menu ;

    function initialize()
    {
        parent::initialize();
        self::$role = new model\Role();
        self::$menu = new model\Menu();

    }

    /**
     * 查看
     */
    public function index(){

        if(Request::isGet()){
            return $this->fetch();
        }


        if(Request::isPost()){

            $post = input('post.');
            if(isset($post['where']) ){

                $where = parseWhere($post['where']);

            }else{
                $where = '1=1';
            }



            $post['page'] = isset($post['page']) ? $post['page'] :1;
            $post['limit'] = isset($post['limit']) ? $post['limit'] :10;


            $list = self::$role->page($post['page'] ,$post['limit'])->where($where)->order('add_time desc')->select()->toArray();
            $list['count'] = self::$role->where($where)->count();
            result($list);
        }
       

    }
    /**
     * 添加
     */
    public function add(){
        return $this->fetch();
    }
    /**
     * 编辑
     */
    public function edit(){
        $id = input('param.id');

        $res = self::$role->find($id)->toArray();

        $this->assign('vo',$res);
        return $this->fetch();
    }

    /**
     * 保存添加
     */
    public function add_action(){
        $post = input('post.');

        $flag = $this->validate($post,'Role.add');
        if($flag !== true)$this->error($flag);

        $flag = self::$role
            ->isUpdate(false)
            ->allowField(true)
            ->save($post);

        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }
    /**
     * 保存编辑
     */
    public function edit_action(){
        $post = input('post.');

        $post['status']  = isset($post['status']) ? $post['status'] : 0;
        $flag = $this->validate($post,'Role.edit');
        if($flag !== true)$this->error($flag);


        $flag = self::$role
            ->isUpdate(true)
            ->allowField(true) //忽略字段不存在的值 比如 repassword
            ->save($post);


        $flag ? $this->success('操作成功','',$post):$this->error('操作失败，请稍后再试');
    }
    /**
     * 删除
     */
    public function del(){
        $post = input('post.');

        if($post['id'] == 1)$this->error('超管权限不允许删除');

        $role = self::$role;
        $flag = $role::destroy($post['id']);

        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }

    /**
     * 批量删除
     */
    public function pdel(){
        $post = input('post.');
        
        if(!isset($post['ids'])) $this->error('请先选择');
        if(in_array(1 ,$post['ids'])) $this->error('超管权限不允许删除');

        $ids = join(',',$post['ids']);
        $flag = self::$role->where('id in('.$ids.')')->delete();
        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }
    /**
     * 冻结
     */
    public function forzen(){
        $post = input('post.');
        if(!isset($post['ids'])) $this->error('请先选择');
        if(in_array(1 ,$post['ids'])) $this->error('超管权限不允许操作');
        $ids = join(',',$post['ids']);

        $flag = self::$role->where('id in('.$ids.')')->update(['status' => 1]);
        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }
    /**
     * 解冻
     */
    public function unforzen(){
        $post = input('post.');
        if(!isset($post['ids'])) $this->error('请先选择');
        if(in_array(1 ,$post['ids'])) $this->error('超管权限不允许操作');
        $ids = join(',',$post['ids']);

        $flag = self::$role->where('id in('.$ids.')')->update(['status' => 0]);
        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }

    /**
     * 权限设置
     */
    public function author(){
        if(Request::isGet()){
            $id = input('param.id');
            if(!$id) $this->error('id is miss');
            if($id == 1) $this->error('超级管理员无需设置');

            $role = self::$role->find($id)->toArray();

            $this->assign('vo' ,$role);
            return $this->fetch();
        }

        if(Request::isPost()){
            $post = input('post.');
            $id = input('param.id');
            if($id == 1) $this->error('超级管理员无需设置');

            $auth_ids = explode(',',$post['auth_ids']);
            $field = 'id,pid,name';
            $list = self::$menu->field($field)->select()->toArray();
            $field = explode(',',$field);
            //创建初始化数组
            foreach($list as $k => $v){
                if(in_array($v['id'] ,$auth_ids)){
                    $v['open'] = $v['checked'] = true;
                }
                //如果第一个元素的pid 不是0 则，默认处理为0
                if($k == 0 && $v[$field[1]] != 0){
                    $v[$field[1]] = 0;
                }
                $tree[ $v[ $field[0] ] ] = $v;
                $tree[ $v[ $field[0] ] ]['son'] = [];
            }
            //引用
            foreach($tree as $sk => $sv){
                //自动生成层级关系
                if($sv[$field[1]] != 0 ){
                    //查找的数据 可能上级的元素不存在
                    if(!isset($tree[$sv[$field[1]]])){
                        continue;
                    }else{
                        //传值引用
                        $tree[ $sv[ $field[1] ] ]['son'][] = &$tree[$sk];
                    }
                }
            }
            //剔除多余元素
            foreach($tree as $k => $v){
                if(isset($v[$field[1]]) && $v[$field[1]] != 0)  unset($tree[$k]);
            }

            sort($tree);

            return $tree;
        }
    }



    /**
     * 保存权限设置
     */
    function author_action(){
        $post = input('post.');
        if(!isset($post['ids']))$this->error('请先选择');

        $data['auth_ids'] = join(',',$post['ids']);

        $data['id'] = $post['id'];
        $flag = self::$role->update($data);
        $flag ? $this->success('操作成功'):$this->error('操作失败，请稍后再试');
    }
}